package org.ctstudio.common.utils;

import java.util.UUID;

public class UUIDUtil {
  public String randomHex() {
    UUID uuid = UUID.randomUUID();
    return uuid.toString().replaceAll("-", "");
  }

  public byte[] randomBytes() {
    return ByteUtil.getInstance().hex2Bytes(randomHex());
  }

  public String randomBase64() {
    return Base64Util.getInstance().toBase64(this.randomBytes());
  }

  public String hexToUUIDString(String hex) {
    if (hex.length() > 32)
      throw new IllegalArgumentException("Length must less than 32.");

    StringBuilder sb = new StringBuilder(32);
    if (hex.length() < 32) {
      for (int i = 0; i < 32 - hex.length(); i++)
        sb.append(0);
    }
    sb.append(hex);
    sb.insert(8, '-');
    sb.insert(13, '-');
    sb.insert(18, '-');
    sb.insert(23, '-');
    return sb.toString();
  }

  public UUID fromHex(String hex) {
    return UUID.fromString(hexToUUIDString(hex));
  }

  public UUID fromBytes(byte[] bytes) {
    return fromHex(ByteUtil.getInstance().bytes2HexUppercase(bytes));
  }

  public UUID fromBase64(String base64) {
    return fromBytes(Base64Util.getInstance().fromBase64(base64));
  }

  private static UUIDUtil _instance;

  public static UUIDUtil getInstance() {
    if (_instance == null) {
      _instance = new UUIDUtil();
    }
    return _instance;
  }
}
